package com.framework.network.factory

import android.content.Context
import com.framework.network.interceptor.*
import okhttp3.OkHttpClient
import okhttp3.Protocol
import org.koin.core.KoinComponent
import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.SSLContext
import javax.net.ssl.X509TrustManager

/**
 * @Description:OkHttp请求配置类
 * @Author: you
 */
class OkHttpClientFactory(private val mContext: Context) : KoinComponent {
    private val builder: OkHttpClient.Builder = OkHttpClient.Builder()

    private val trustManager: X509TrustManager = cert()

    /**
     * 配置相关证书
     */
    private fun cert(): X509TrustManager {
        return object : X509TrustManager {
            override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
                //Empty
            }

            override fun getAcceptedIssuers(): Array<X509Certificate?> =
                arrayOfNulls(0)

            override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {
                //Empty
            }
        }
    }

    /**
     * 配置host-verifier
     */
    private fun hostnameVerifier(): HostnameVerifier {
        return HostnameVerifier { _, _ ->
            true
        }
    }

    /**
     * 配置协议
     */
    private fun protocol() {
        builder.protocols(mutableListOf(Protocol.HTTP_1_1))
    }

    /**
     * 配置Https相关
     */
    private fun https() {
        val context = SSLContext.getInstance("TLS")
        context.init(null, arrayOf(trustManager), SecureRandom())
        builder.hostnameVerifier(hostnameVerifier())
        builder.sslSocketFactory(context.socketFactory, trustManager)
    }

    /**
     * 设置拦截器
     */
    private fun interceptor() {
        builder.addInterceptor(DynamicTimeoutInterceptor())//接口设置超时时间拦截器
        builder.addInterceptor(HeadParamsInterceptor(mContext))//设置head的拦截器
        builder.addInterceptor(CommonParamsInterceptor(mContext))//设置公参拦截器
        builder.addInterceptor(UrlReplaceInterceptor(mContext))//设置url替换的拦截器
        builder.addInterceptor(LogWithRequestInterceptor(mContext))//日志拦截器
        builder.addInterceptor(NetworkStatusInterceptor(mContext))//网络状态拦截器
    }


    /**
     * 构建OkHttpClient对象
     */
    fun create(): OkHttpClient {
        interceptor()
        protocol()
        https()
        return builder.build()
    }
}